package com.ocean.common.utils.file;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.IURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

/**
* Title: WordToHtml
* Description:
* @author dingxy
* @date 2018年12月3日
*/
public class WordToHtmlUtils {

	public static String wordConvertToHtml(String wordPath,String htmlPath,String newFilename) throws TransformerException, IOException, ParserConfigurationException {
		String filePath = convert2Html(wordPath, htmlPath, newFilename);
		String attrstemp =filePath.replace("\\", ",").replace("/",",").replace("//",",");
        String[] attrs = attrstemp.split(",");
        // 对路径进行截取
        String name1 = attrs[attrs.length-3];
		String name2 = attrs[attrs.length-2];
		String name3 = attrs[attrs.length-1];
		filePath = name1+File.separator+name2+File.separator+name3;
		//截取后 DOCPREVIEW\NMF_BEN_OSM_CSDT_2018112612_072h_SSW\NMF_BEN_OSM_CSDT_2018112612_072h_SSW.html
		return filePath;
    }

	private static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            if(!file.exists()){

            }
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos));
            bw.write(content);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (fos != null)
                    fos.close();
            } catch (IOException ie) {
            }
        }
    }

    /**
     * Title: convert2Html
     * Description:  将word转换成html
     * @param fileName  word文件名
     * @param suffixName word 的后缀, doc类型 或者是 docx类型
     * @param outPutFilePath  生成的html存储路径
     * @param  oldFileName  原word名。新生成的html命名规则是原来word的前缀名称不改变，后面添加html。
     * @throws TransformerException
     * @throws IOException
     * @throws ParserConfigurationException
     */
    private static String convert2Html(String wordPath, String outPutFilePath,String oldFileName)
            throws TransformerException, IOException,
            ParserConfigurationException {

    	String prefixFileName = oldFileName.substring(0,oldFileName.lastIndexOf(".")); //获取前缀名
    	String suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")+1);   // 获取后缀类型(doc或者docx)
    	//String endPath=outPutFilePath+prefixFileName;
    	String endPath="";
    	if("doc".equals(suffixName)){
    		endPath=outPutFilePath+"DOCPREVIEW"+File.separator;
    	}else{
    		endPath=outPutFilePath+"DOCXPREVIEW"+File.separator;
    	}
    	endPath=endPath+prefixFileName+File.separator;
    	File file = new File(endPath);
    	if (!file.exists()) { //判断是否存在
    		file.mkdirs();
    	}

    	ByteArrayOutputStream out = new ByteArrayOutputStream();

    	/**
    	 * word2007和word2003的构建方式不同，
    	 * 前者的构建方式是xml，后者的构建方式是dom树。
    	 * 文件的后缀也不同，前者后缀为.docx，后者后缀为.doc
    	 * 相应的，apache.poi提供了不同的实现类。
    	 */
    	if("docx".equals(suffixName)){
    		//step 1 : load DOCX into XWPFDocument
    		InputStream inputStream = new FileInputStream(new File(wordPath));
    		XWPFDocument document = new XWPFDocument(inputStream);

    		//step 2 : prepare XHTML options
    		//final String imageUrl = "";

    		XHTMLOptions options = XHTMLOptions.create();
    		//options.setExtractor(new FileImageExtractor(new File(endPath + imageUrl)));
    		options.setExtractor(new FileImageExtractor(new File(endPath)));
    		options.setIgnoreStylesIfUnused(false);
    		options.setFragment(true);
    		options.URIResolver(new IURIResolver() {
    			@Override
				public String resolve(String uri) {
    				return  uri;
    			}
    		});

    		//step 3 : convert XWPFDocument to XHTML
    		XHTMLConverter.getInstance().convert(document, out, options);

    	}else{
	        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(wordPath));
	        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
	                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
	         wordToHtmlConverter.setPicturesManager(new PicturesManager(){
	             @Override
				 public String savePicture(byte[] content,
										   PictureType pictureType, String suggestedName,
										   float widthInches, float heightInches ){

	                 return suggestedName;
	             }
	         });
	        wordToHtmlConverter.processDocument(wordDocument);
	        //save pictures
	        List pics=wordDocument.getPicturesTable().getAllPictures();
	        if(pics!=null){
	            for(int i=0;i<pics.size();i++){
	                Picture pic = (Picture)pics.get(i);
	                try {
	                    pic.writeImageContent(new FileOutputStream(endPath +File.separator+ pic.suggestFullFileName()));
	                } catch (FileNotFoundException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        Document htmlDocument = wordToHtmlConverter.getDocument();
	        DOMSource domSource = new DOMSource(htmlDocument);
	        StreamResult streamResult = new StreamResult(out);

	        TransformerFactory tf = TransformerFactory.newInstance();    //这个应该是转换成xml的
	        Transformer serializer = tf.newTransformer();
	        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
	        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
	        serializer.setOutputProperty(OutputKeys.METHOD, "html");
	        serializer.transform(domSource, streamResult);
    	}

    	out.close();
    	writeFile(new String(out.toByteArray()), endPath+File.separator+prefixFileName+".html");

    	try { // 保证上面的文件流能操作完
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		//return endPath+File.separator+prefixFileName+".html";
    	return endPath+prefixFileName+".html";
    }

}
